//
//  SacnResultView.swift
//  miaoyin
//
//  Created by David on 2017/3/18.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class ScanResultView: UIView, UITableViewDelegate, UITableViewDataSource {
    
    private var selIndex = 0
    
    var fileList: NSArray?
    
    var selectedIndex: Int{
        return selIndex
    }
    
    var mCode: String?
    
    var cardView: UIView!
    
    var printStatusView: UIImageView!
    var printStatusLabel: UILabel!
    
    var printing = false
    var tableView: UITableView!
    
    var submitBtn: UIButton!
    
    var pluseIndicate = 0
    let tttime = 5
    let overtime = 60
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let bgView = UIVisualEffectView(frame: frame)
        bgView.effect = UIBlurEffect(style: .dark)
        addSubview(bgView)
        
        printStatusView = UIImageView(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
        printStatusView.image = #imageLiteral(resourceName: "printer_white")
        printStatusView.center = CGPoint(x: frame.width/2, y: frame.height/2)
        bgView.addSubview(printStatusView)
        
        printStatusLabel = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width - 32, height: 20))
        printStatusLabel.center = CGPoint(x: frame.width/2, y: frame.height/2 + printStatusView.frame.height/2 + 20)
        printStatusLabel.font = UIFont.systemFont(ofSize: 14)
        printStatusLabel.textColor = UIColor.white
        printStatusLabel.textAlignment = .center
        printStatusLabel.text = "请稍后"
        bgView.addSubview(printStatusLabel)
        
        printStatusView.alpha = 0
        printStatusLabel.alpha = 0
        
        cardView = UIView(frame: CGRect(x: 16, y: 0, width: frame.width - 32, height: 4*44))
        cardView.center = CGPoint(x: frame.width/2, y: frame.height/2)
        cardView.backgroundColor = UIColor.white
        cardView.layer.cornerRadius = 8
        bgView.addSubview(cardView)
        
        let titleBar = UIView(frame: CGRect(x: 0, y: 0, width: cardView.frame.width, height: 44))
        cardView.addSubview(titleBar)
        
        let closeBtn = UIButton(frame: CGRect(x: 16, y: 0, width: 44, height: 44))
        closeBtn.setTitle("×", for: .normal)
        closeBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24)
        closeBtn.setTitleColor(themeColor2, for: .normal)
        titleBar.addSubview(closeBtn)
        closeBtn.addTarget(self, action: #selector(ScanResultView.hideView), for: .touchUpInside)
        
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: cardView.frame.width - (16+44)*2, height: 44))
        titleLabel.center.x = cardView.frame.width/2
        titleLabel.text = "选择打印文件"
        titleLabel.textAlignment = .center
        titleBar.addSubview(titleLabel)
        
        tableView = UITableView(frame: CGRect(x: 0, y: 66, width: cardView.frame.width, height: 44))
        tableView.delegate = self
        tableView.dataSource = self
        cardView.addSubview(tableView)
        
        submitBtn = UIButton(frame: CGRect(x: 16, y: cardView.frame.height-52, width: cardView.frame.width-32, height: 44))
        submitBtn.layer.cornerRadius = 8
        submitBtn.backgroundColor = themeColor1
        submitBtn.setTitle("打印", for: .normal)
        submitBtn.setTitleColor(UIColor.white, for: .normal)
        cardView.addSubview(submitBtn)
        submitBtn.addTarget(self, action: #selector(ScanResultView.submitPrint), for: .touchUpInside)
        
        alpha = 0
        
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ScanResultView.plusePrintStauts), userInfo: nil, repeats: true)
        
        
    }
    
    func showView(code: String?){
        fileList = nil
        tableView.reloadData()
        selIndex = 0
        
        cardView.alpha = 1
        
        UIView.animate(withDuration: 0.3) { 
            self.alpha = 1
        }
        
        mCode = code
        
        var req = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=Goods&a=queryOrder")!)
        req.httpMethod = "POST"
        req.httpBody = "type=2".data(using: .utf8)
        
        
        URLSession.shared.dataTask(with: req) { (data:Data?, re:URLResponse?, err:Error?) in
            do{
                if err != nil{
                    throw err!
                }
                
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                self.fileList = jsonObj?.object(forKey: "data") as? NSArray
                
                DispatchQueue.main.async {
                    var dataHeight = 1
                    if self.fileList != nil{
                        if self.fileList!.count > 0{
                            dataHeight = self.fileList!.count
                        }
                    }
                    self.cardView.frame = CGRect(x: 0, y: 0, width: self.cardView.frame.width, height: CGFloat(dataHeight+3)*44)
                    self.tableView.frame = CGRect(origin: self.tableView.frame.origin, size: CGSize(width: self.tableView.frame.width, height: CGFloat(dataHeight)*44))
                    self.cardView.center = CGPoint(x: self.frame.width/2, y: self.frame.height/2)
                    self.submitBtn.center.y = self.cardView.frame.height - 30
                    self.tableView.reloadData()
                }
                
            }catch let ex{
                print(ex)
            }
        }.resume()
    }
    
    
    
    func submitPrint(){
        
        if fileList != nil{
            if fileList!.count > 0{
                let fileItem = fileList?.object(at: selIndex) as? NSDictionary
                
                let orderID = fileItem?.object(forKey: "or_num") as? String
                print(orderID ?? "nil")
                
                
                if mCode != nil && orderID != nil{
                    print("打印取件")
                    printStatusView.image = #imageLiteral(resourceName: "printer_white")
                    printStatusLabel.text = "请稍后"
                    UIView.animate(withDuration: 0.3, animations: { 
                        self.cardView.alpha = 0
                    })
                    
                    UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveLinear, animations: { 
                        self.printStatusView.alpha = 1
                        self.printStatusLabel.alpha = 1
                    }, completion: nil)
                    
                    var req = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=takeGoods")!)
                    req.httpMethod = "POST"
                    req.httpBody = "\(mCode!)&ornum=\(orderID!)".data(using: .utf8)
                    
                    URLSession.shared.dataTask(with: req, completionHandler: { (data:Data?, re:URLResponse?, err:Error?) in
                        
                        
                        do{
                            if err != nil{
                                throw err!
                            }
                            print(String(data: data!, encoding: .utf8) ?? "data nil")
                            
                            let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                            let code = jsonObj?.object(forKey: "code") as? Int
                            
                            
                            if code == 200{
                                DispatchQueue.main.async {
                                    self.printStatusLabel.text = "打印中"
                                }
                                self.pluseIndicate = 0
                                self.printing = true
                                
                            }else{
                                let msg = jsonObj?.object(forKey: "message") as? String
                                DispatchQueue.main.async {
                                    self.printComplete(2, msg)
                                }
                            }
                            
                        }catch let ex{
                            DispatchQueue.main.async {
                                self.printComplete(2, nil)
                            }
                            print(ex)
                        }
                    }).resume()
                }
            }
        }
    }
    
    
    
    func plusePrintStauts(){
        if printing {
            
            pluseIndicate += 1
            
            if pluseIndicate % tttime == 0{
                var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=business&a=clientPrintFileStatus")!)
                resq.httpMethod = "POST"
                
                if mCode == nil{
                    printComplete(2, nil)
                    return
                }else{
                    resq.httpBody = "\(mCode!)".data(using: .utf8)
                }
//                let fileItem = fileList?.object(at: selIndex) as? NSDictionary
//                let orderID = fileItem?.object(forKey: "or_num") as? String
//                if orderID == nil{
//                    
//                }else{
//                    resq.httpBody = "num=\(orderID!)".data(using: .utf8)
//                }
                
                URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, re:URLResponse?, err:Error?) in
                    do{
                        if err != nil{
                            throw err!
                        }
                        
                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                        
                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        let code = jsonObj?.object(forKey: "code") as? Int
                        
                        
                        if code == 200{
                            DispatchQueue.main.async {
                                self.printComplete(0, nil)
                            }
                        }else if code == 201 {
                            if self.pluseIndicate >= self.overtime {
                                let msg = jsonObj?.object(forKey: "message") as? String
                                DispatchQueue.main.async {
                                    self.printComplete(1, msg)
                                }
                            }
                        }else{
                            let msg = jsonObj?.object(forKey: "message") as? String
                            DispatchQueue.main.async {
                                self.printComplete(1, msg)
                            }
                        }
                        
                    }catch let ex{
                        DispatchQueue.main.async {
                            self.printComplete(1, nil)
                        }
                        print(ex)
                    }
                }).resume()
            }
            
        }
    }
    
    func printComplete(_ result: Int,  _ msg: String?){
        printing = false
        pluseIndicate = 0
        switch result {
        case 0:
            
            printStatusLabel.text = "打印完成"
            printStatusView.image = #imageLiteral(resourceName: "finish")
            
            break
        case 1:
            
            printStatusLabel.text = "获取打印状态失败"
            printStatusView.image = #imageLiteral(resourceName: "warning")
            
            break
        case 2:
            
            printStatusLabel.text = "打印失败"
            printStatusView.image = #imageLiteral(resourceName: "warning")
            
            break
        default:
            break
        }
        
        if result != 0 && msg != nil {
            printStatusLabel.text = msg
        }
        
        UIView.animate(withDuration: 0.3, delay: 2, options: .curveLinear, animations: { 
            self.alpha = 0
        }, completion: nil)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if fileList == nil{
            return 1
        }else{
            return fileList!.count > 0 ? fileList!.count : 1
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "pay")
        if selIndex == indexPath.row{
            cell.accessoryType = .checkmark
        }else{
            cell.accessoryType = .none
        }
        
        let iconView = UIImageView(frame: CGRect(x: 16, y: 8, width: 28, height: 28))
        cell.addSubview(iconView)
        
        
        let titleLabel = UILabel(frame: CGRect(x: 52, y: 8, width: frame.width - 128, height: 28))
        titleLabel.font = UIFont.systemFont(ofSize: 14)
//        titleLabel.text = Fatcat.payMethods[indexPath.row]["name"]
        cell.addSubview(titleLabel)
        
        if fileList == nil{
            titleLabel.text = "暂无可打印的文件"
            return cell
        }else{
            if fileList!.count > 0{
                iconView.image = #imageLiteral(resourceName: "doc_icon")
                let fileItem = fileList?.object(at: indexPath.row) as? NSDictionary
                titleLabel.text = fileItem?.object(forKey: "sourcefilename") as? String ?? "文件名"
                return cell
            }else{
                titleLabel.text = "暂无可打印的文件"
                return cell
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selIndex = indexPath.row
        tableView.deselectRow(at: indexPath, animated: true)
        
        tableView.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .automatic)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func hideView(){
        UIView.animate(withDuration: 0.3) { 
            self.alpha = 0
        }
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
